package com.huike.key_listener;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){//使用handler做单双击监听
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what ==  1){//单机
                Log.e("---","单机");
                finish();//关闭页面
                isClick = false;//改为单机标识
            }

        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApplication.getInstance().addActivity(this);//将所有页面添加任务栈

    }

    private Boolean isClick = false;//是否点击
    //全局监听返回按钮
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if(event.getKeyCode() ==KeyEvent.KEYCODE_BACK){

            if(isClick){//双击
                isClick = false;
                Toast.makeText(this, "退出APP", Toast.LENGTH_SHORT).show();
                BaseApplication.getInstance().exit();
                return false;
            }else{//单机
                isClick = true;
                handler.sendEmptyMessageDelayed(1,200);//发送延迟消息
                return  false;//返回 false 不处理key事件（不会关闭当前页面）
            }

        }

        return super.onKeyUp(keyCode, event);
    }



    //监听长按
    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {

        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){
            Toast.makeText(this, "退出APP", Toast.LENGTH_SHORT).show();
            BaseApplication.getInstance().exit();//关闭所有页面
            return true;//消费
        }

        return super.onKeyLongPress(keyCode, event);
    }

}
